//
//  AliyunImageUploadManager.swift
//  XiaoweHearingAid
//
//  Created by edy on 2024/11/12.
//

import Foundation

class AliyunImageUploadManager {
    
    /// 上传图片
    class func uploadImages(imageList: [UIImage], completion: @escaping (_ imageUrlList: [String]) -> Void) {
        let cmdId = "上传图片到Ali云"
        if imageList.isEmpty {
            completion([])
            return
        }
        getOssStsToken { cModel in
//            DispatchQueue.main.async {
                guard let cModel = cModel else {
                    completion([])
                    return
                }
            AliyunUploadManager.uploadImages(imageList, aliyunCredential: cModel) { json in
                    DispatchQueue.main.async {
                        let cImageUrls = json
                        guard !cImageUrls.isEmpty else {
                            completion([])
                            return
                        }
                        
                        completion(cImageUrls)
                    }
                } failure: { eString in
                    log.error("\(cmdId)失败 error = \(eString)")

                    DispatchQueue.main.async {
                        completion([])
                    }
                }
//            }
        }
    }
    
    /// 获取图片临时token
    class func getOssStsToken(completion: @escaping (AliyunCredentialModel?) -> Void) {
        let cmdId = "获取图片临时token"
        AppPublicNetworkServiceManager.getOssStsToken { error in
            log.error("\(cmdId), 上传图片失败 \(error)")
            completion(nil)
        } successHandler: { response in
            guard let credentialModel = response.data as? AliyunCredentialModel else {
                log.error("\(cmdId), 上传图片失败, 获取的 AliyunCredentialModel 为空")
                completion(nil)
                return
            }
            
            completion(credentialModel)
        }
    }
    
}
